// src/views/banner/Add.tsx
import { Space, Input, Button, Image, message } from 'antd';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { addBanner } from '../../api/banner';

type AddProps = {}

export const Add = (props: AddProps) => {

    // 这里我们直接调用 Input 相关，没有使用 Form
    const [alt, setAlt] = useState<string>('')
    const [link, setLink] = useState<string>('')
    const [url, setUrl] = useState('')

    // 文件上传，选择了文件后，咱们要拿到系统文件的内容
    const getImgUrl = () => {
        const img = document.getElementById('img') as HTMLInputElement
        const files = img && img.files
        const file = files && files[0]
        const reader = new FileReader()
        reader.readAsDataURL(file!)
        reader.onload = function () {
            setUrl(this.result!.toString())
        }
    }
    const navigate = useNavigate()
    return (
        <Space direction='vertical' style={{ width: 300 }}>
            <Input placeholder='提示信息' value={alt} onChange={e => setAlt(e.target.value)} />
            <Input placeholder='链接地址' value={link} onChange={e => setLink(e.target.value)} />
            <Input type="file" id='img' onChange={getImgUrl} />
            <div>
                预览图片:
                <Image src={url} width={300} />
            </div>
            <Button type='primary' onClick={() => {
                if (alt === '' || link === '' || url === '') {
                    message.error('请先完成表单输入')
                    return
                }
                addBanner({
                    alt, link, img: url
                }).then(() => {
                    navigate('/banner/home')
                })
            }}>添加</Button>
        </Space>
    );
}